package com.yk.silence.rxretrofitmvp.base.mvp;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yk.silence.rxretrofitmvp.base.model.BaseModel;
import com.yk.silence.rxretrofitmvp.base.mvp.BaseMVP;
import com.yk.silence.rxretrofitmvp.base.presenter.BasePresenter;
import com.yk.silence.rxretrofitmvp.base.view.BaseView;

public abstract class BaseMVPFragment<V extends BaseView, M extends BaseModel, P extends BasePresenter>
        extends Fragment implements BaseMVP<V, M, P> {

    private P presenter;
    //视图是否创建
    protected boolean isViewCreated = false;
    //数据是否加载完成
    private boolean isLoadDataCompleted;
    private Activity mActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
        presenter = createPresenter();
        if (presenter != null) {
            presenter.registerView(createView());
            presenter.registerModel(createModel());
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(getFragmentId(), container, false);
        initView(rootView);
        isViewCreated = true;
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(getUserVisibleHint()){
            lazyLoadData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isViewCreated && !isLoadDataCompleted){
            lazyLoadData();
        }else{
            isLoadDataCompleted = false;
            isViewCreated = false;
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (presenter != null) {
            presenter.onDestroy();
        }
    }

    /**
     * 获取布局
     *
     * @return
     */
    protected abstract int getFragmentId();

    /**
     * 初始化布局
     *
     * @param view
     */
    protected abstract void initView(View view);

    /**
     *懒加载
     */
    public  void lazyLoadData() {
        isLoadDataCompleted=true;
    }

    /**
     * 线程
     * @param r
     */
    public void runOnUIThread(Runnable r) {
        final Activity activity = getActivity();
        if (activity != null && r != null)
            activity.runOnUiThread(r);
    }
}
